package com.easyfile.easyfilemaster.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.easyfile.easyfilemaster.entity.UserInfo;
import com.easyfile.easyfilemaster.entity.base.ResultFactory;
import com.easyfile.easyfilemaster.utils.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * token校验拦截器
 * @author chenpeman
 * @date 2022年05月05日 22:10
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token= request.getHeader("X-Token");
        //设置编码格式
        response.setCharacterEncoding("UTF-8");
        //解决乱码
        response.setHeader("Content-Type", "text/html;charset=UTF-8");

        if (token==null){
            response.getWriter().write(JSONObject.toJSONString(ResultFactory.unauthorized("非法请求")));
            return false;
        }

        boolean access = JwtUtil.checkTokenAccess(token);
        if (!access){
            response.getWriter().write(JSONObject.toJSONString(ResultFactory.unauthorized("登陆状态已过期")));
            return false;
        }
        //放行
        return true;
    }
}
